<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">员工管理</span>
      <el-button type="primary" style="float: right; margin-top: 13px;"
                 @click="beforeAddEmployee">新增员工
      </el-button>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form label-width="80px" label-position="top" :model="employeeForm" :rules="rules" ref="employeeForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="employeeForm.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="employeeForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="employeeForm.idCard" placeholder="请输入身份证号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="employeeForm.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="employeeForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="departmentId">
              <el-select v-model="employeeForm.departmentId" placeholder="请选择部门" style="width:100%">
                <el-option v-for="dept in departmentOptions"
                           :key="dept.id"
                           :label="dept.name"
                           :value="dept.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职时间" prop="entryDate">
              <el-date-picker
                  v-model="employeeForm.entryDate"
                  type="date"
                  placeholder="选择入职日期"
                  style="width:100%"
                  value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职级" prop="level">
              <el-select v-model="employeeForm.level" placeholder="请选择职级" style="width:100%">
                <el-option label="普通员工" value="10"></el-option>
                <el-option label="部门主管" value="20"></el-option>
                <el-option label="部门经理" value="30"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="上级" prop="parentId">
          <el-select
              v-model="employeeForm.parentId"
              placeholder="请选择上级"
              filterable
              style="width:100%">
            <el-option
                v-for="emp in employeeOptions"
                :key="emp.id"
                :label="emp.name"
                :value="emp.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-dialog>

    <el-card style="margin: 20px;height: 70px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="用户搜索" style="width: 270px;">
          <el-input placeholder="请输入姓名"
                    v-model="searchEmployeeForm.name" @change="loadEmployee"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadEmployee">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin: 20px;">
      <el-table :data="employeeArr">
        <el-table-column label="编号" type="index" width="80" align="center"></el-table-column>
        <el-table-column label="姓名" prop="name" align="center"></el-table-column>
        <el-table-column label="性别" prop="gender" align="center"></el-table-column>
        <el-table-column label="身份证号" prop="idCard" align="center"></el-table-column>
        <el-table-column label="联系电话" prop="phone" align="center"></el-table-column>
        <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
        <el-table-column label="部门" align="center">
          <template #default="{row}">
            {{ formatDepartment(row.departmentId) }}
          </template>
        </el-table-column>
        <el-table-column label="入职时间" prop="entryDate" align="center"></el-table-column>
        <el-table-column label="职级" align="center">
          <template #default="{row}">
            {{ formatLevel(row.level) }}
          </template>
        </el-table-column>
        <el-table-column label="上级" prop="parentId" align="center" width="200">
          <template #default="{row}">
            {{ formatParent(row.parentId) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="text"
                       :disabled="scope.row.level == 40" @click="editEmployee(scope.row)">编辑</el-button>
            <el-button link type="text"
                       :disabled="scope.row.level == 40" @click="deleteEmployee(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          style="margin-top: 20px;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[3, 4, 5]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import qs from "qs";
import axios from "axios";
import { Message } from 'element-ui';

export default {
  data() {
    // 身份证验证规则
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入身份证号'));
      }
      // 简单的身份证格式验证
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!reg.test(value)) {
        callback(new Error('身份证号格式不正确'));
      } else {
        callback();
      }
    };

    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入联系电话'));
      }
      const reg = /^1[3-9]\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error('手机号格式不正确'));
      } else {
        callback();
      }
    };

    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入邮箱'));
      }
      const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!reg.test(value)) {
        callback(new Error('邮箱格式不正确'));
      } else {
        callback();
      }
    };

    return {
      getUser: this.$getUser(),
      dialogTitle: '新增员工',
      dialogVisible: false,
      searchEmployeeForm: {
        name: ''
      },
      employeeArr: [],
      departmentOptions: [],
      employeeOptions: [],
      employeeForm: {
        id: null,
        name: '',
        gender: '男',
        idCard: '',
        phone: '',
        email: '',
        departmentId: null,
        entryDate: '',
        level: '10',
        parentId: null
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        idCard: [
          { validator: validateIdCard, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        entryDate: [
          { required: true, message: '请选择入职日期', trigger: 'change' }
        ],
        level: [
          { required: true, message: '请选择职级', trigger: 'change' }
        ]
      },
      pagination: {
        current: 1,
        size: 3,
        total: 0
      }
    };
  },
  mounted() {
    this.loadEmployee();
    this.loadDepartments();
    this.loadAllEmployees();
  },
  methods: {
    // 加载员工列表
    loadEmployee() {
      let data = qs.stringify({
        ...this.searchEmployeeForm,
        pageCurrent: this.pagination.current,
        pageSize: this.pagination.size
      });

      axios.get(this.$BASE_URL + '/v1/user/list?'+data)
          .then((res) => {
            console.log(res.data.data)
            if (res.data.state === 2000) {
              this.employeeArr = res.data.data.userList || [];
              this.pagination.total = res.data.data.total;
            } else {
              Message.error(res.data.message);
            }
          })
    },

    // 加载部门列表
    loadDepartments() {
      axios.get(this.$BASE_URL + '/v1/department/list')
          .then((res) => {
            if (res.data.state === 2000) {
              this.departmentOptions = res.data.data;
            }
          });
    },

    // 加载所有员工(用于上级选择)
    loadAllEmployees() {
      axios.get(this.$BASE_URL + '/v1/user/list')
          .then((res) => {
            if (res.data.state === 2000) {
              this.employeeOptions = res.data.data.userList || [];
            }
          });
    },

    // 重置搜索
    resetSearch() {
      this.searchEmployeeForm = {
        name: ''
      };
      this.pagination.current = 1;
      this.loadEmployee();
    },

    // 提交表单
    submit() {
      this.$refs.employeeForm.validate((valid) => {
        if (valid) {
          axios.post(this.$BASE_URL + '/v1/user/save', qs.stringify(this.employeeForm))
              .then((res) => {
                if (res.data.state === 2000) {
                  this.handleClose();
                  this.loadEmployee();
                  this.loadAllEmployees(); // 刷新上级选择列表
                  Message.success("保存成功!");
                } else {
                  Message.error(res.data.message);
                }
              });
        }
      });
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false;
      this.$refs.employeeForm.resetFields();
      this.employeeForm = {
        id: null,
        name: '',
        gender: '男',
        idCard: '',
        phone: '',
        email: '',
        departmentId: null,
        entryDate: '',
        level: '10',
        parentId: null
      };
    },

    // 准备新增员工
    beforeAddEmployee() {
      this.dialogTitle = '新增员工';
      this.dialogVisible = true;
    },

    // 编辑员工
    editEmployee(row) {
      this.dialogTitle = '编辑员工';
      this.dialogVisible = true;

      // 使用$nextTick确保表单已渲染
      this.$nextTick(() => {
        this.employeeForm = {
          id: row.id,
          name: row.name,
          gender: row.gender,
          idCard: row.idCard,
          phone: row.phone,
          email: row.email,
          departmentId: row.departmentId,
          entryDate: row.entryDate,
          level: row.level,
          parentId: row.parentId
        };
      });
    },

    // 删除员工
    deleteEmployee(id) {
      this.$confirm('确定要删除该员工吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post(this.$BASE_URL + `/v1/user/delete/${id}`)
            .then((res) => {
              if (res.data.state === 2000) {
                Message.success('删除成功');
                this.loadEmployee();
                this.loadAllEmployees(); // 刷新上级选择列表
              } else {
                Message.error(res.data.message);
              }
            });
      })
      .catch(() => {
        Message.info('已取消删除');
      });
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size;
      this.loadEmployee();
    },

    // 当前页改变
    handleCurrentChange(current) {
      this.pagination.current = current;
      this.loadEmployee();
    },

    // 格式化职级显示
    formatLevel(level) {
      const levelMap = {
        '10': '普通员工',
        '20': '部门主管',
        '30': '部门经理',
        '40': '总经理'
      };
      return levelMap[level] || level;
    },
    // 格式化部门显示
    formatDepartment(departmentId) {
      const department = this.departmentOptions.find(dept => dept.id === departmentId);
      return department ? department.name : departmentId;
    },

    // 格式化上级显示
    formatParent(parentId) {
      const parent = this.employeeOptions.find(emp => emp.id === parentId);
      return parent ? parent.name : '无';
    },
  }
};
</script>

<style scoped>

</style>